<script setup>
import { ref, onMounted } from 'vue'
import SideMenu from './components/SideMenu.vue'
import ChatContainer from './components/ChatContainer.vue'
import LoadingState from './components/LoadingState.vue'
import AdminPanel from './components/AdminPanel.vue'
import '@fortawesome/fontawesome-free/css/all.css'
import './index.css'

const isLoading = ref(false)
// 当前页面
const currentPage = ref('chat')  // 设置初始页面为智能对话

// 功能菜单项 - 更新更丰富的颜色
const menuItems = [
  {
    id: 'chat',
    name: '智能对话',
    icon: 'fa-comments',
    color: 'bg-gradient-to-br from-blue-500 to-indigo-600'
  },
  {
    id: 'knowledge',
    name: '知识问答',
    icon: 'fa-book',
    color: 'bg-gradient-to-br from-purple-500 to-pink-600'
  },
  {
    id: 'meeting',
    name: '会议记录',
    icon: 'fa-clipboard',
    color: 'bg-gradient-to-br from-green-500 to-teal-600'
  },
  {
    id: 'task',
    name: '任务管理',
    icon: 'fa-tasks',
    color: 'bg-gradient-to-br from-emerald-500 to-teal-600'
  },
  {
    id: 'health',
    name: '健康助手',
    icon: 'fa-heartbeat',
    color: 'bg-gradient-to-br from-amber-500 to-orange-600'
  },
  {
    id: 'weather',
    name: '天气查询',
    icon: 'fa-cloud-sun',
    color: 'bg-gradient-to-br from-sky-500 to-cyan-600'
  }
]

// API 基础URL
const API_BASE_URL = 'http://localhost:5000/api'

// 登录相关
const showAuthModal = ref(false)
const isLogin = ref(true)
const username = ref('')
const password = ref('')
const email = ref('')
const user = ref(null)
const authError = ref('')

// 角色选择
const role = ref('user')

// 管理员面板
const showAdminPanel = ref(false)

// 获取页面标题
const getPageTitle = (pageId) => {
  const item = menuItems.find(item => item.id === pageId)
  return item ? item.name : '对话'
}

// 检查用户是否已登录
const checkUserLoggedIn = () => {
  const token = localStorage.getItem('token')
  return !!token && !!user.value
}

// 处理页面切换
const handlePageChange = async (page) => {
  // 检查用户是否已登录
  if (!checkUserLoggedIn()) {
    // 如果未登录，显示登录弹窗
    openAuth(true)
    return
  }
  
  console.log(`切换页面: ${currentPage.value} -> ${page}`)
  
  // 已登录，正常切换页面
  currentPage.value = page
  
  // 切换页面后，获取该页面类型的对话历史
  try {
    isLoading.value = true
    await fetchConversations()
  } catch (error) {
    console.error(`切换页面时获取对话历史失败:`, error)
    
    // 如果获取对话历史失败，创建一个新对话
    // 生成唯一的对话ID
    const conversationId = Date.now().toString()
    
    const newConv = { 
      id: conversationId, 
      title: `新${getPageTitle(page)}对话`, 
      messages: [],
      page_type: page
    }
    
    conversations.value = [newConv]
    currentConversationId.value = newConv.id
    nextId.value = 1
    console.log(`创建了新的${page}对话: ${conversationId}`)
  } finally {
    isLoading.value = false
  }
}

// 处理新建对话
const handleNewChat = async () => {
  // 检查用户是否已登录
  if (!checkUserLoggedIn()) {
    // 如果未登录，显示登录弹窗
    openAuth(true)
    return
  }
  
  // 生成唯一的对话ID
  const conversationId = Date.now().toString()
  
  // 根据当前页面类型设置标题
  const pageTitle = getPageTitle(currentPage.value)
  
  // 创建欢迎消息
  const welcomeMessages = {
    chat: '你好！我是多功能智能助手，可以回答问题、提供知识、规划任务、进行情感交流、健康咨询以及文化学习。有什么我可以帮到你的吗？',
    weather: '欢迎使用天气查询功能。请输入城市名称，我会为你查询天气信息。',
    knowledge: '欢迎使用知识库问答功能。你可以上传PDF、TXT或DOCX文件创建个人知识库，然后询问相关问题，我会基于你的知识库内容回答。',
    task: '欢迎使用任务规划功能。你可以创建任务，例如："创建一个明天下午3点提交报告的任务"，我会帮你设置任务和提醒。',
    health: '欢迎使用健康咨询功能。我可以提供一般性的健康建议，但请记住我不是专业医生，严重问题请咨询医疗专业人士。',
    meeting: '欢迎使用会议记录功能。你可以上传会议文档(PDF、TXT或DOCX)或会议录音文件(MP3、WAV等)，或直接输入会议内容，我会帮你整理会议要点、提取行动项目并生成会议总结。音频文件将使用千问大模型进行处理。'
  }
  
  // 初始消息
  const initialMessages = []
  if (welcomeMessages[currentPage.value]) {
    initialMessages.push({
      type: 'assistant',
      content: welcomeMessages[currentPage.value],
      timestamp: new Date().toISOString()
    })
  }
  
  const newConv = { 
    id: conversationId, 
    title: `新${pageTitle}对话`, 
    messages: initialMessages,
    page_type: currentPage.value
  }
  
  console.log(`创建新对话: ID=${conversationId}, 页面类型=${currentPage.value}`)
  conversations.value.unshift(newConv)
  currentConversationId.value = newConv.id
  nextId.value++
}

// 打开登录/注册模态框
const openAuth = (login = true) => {
  isLogin.value = login
  showAuthModal.value = true
  username.value = ''
  password.value = ''
  email.value = ''
  authError.value = ''
}

// 关闭登录/注册模态框
const closeAuth = () => {
  showAuthModal.value = false
}

// 处理登录/注册
const handleAuth = async () => {
  if (!username.value || !password.value) {
    authError.value = '用户名和密码不能为空'
    return
  }
  
  if (!isLogin.value && !email.value) {
    authError.value = '注册需要提供邮箱'
    return
  }
  
  try {
    const endpoint = isLogin.value ? '/login' : '/register'
    
    // 添加调试信息
    console.log(`正在发送${isLogin.value ? '登录' : '注册'}请求到: ${API_BASE_URL}${endpoint}`)
    console.log('请求体:', JSON.stringify({
      username: username.value,
      password: password.value,
      email: email.value,
      role: role.value
    }))
    
    const response = await fetch(`${API_BASE_URL}${endpoint}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username.value,
        password: password.value,
        email: email.value,
        role: role.value
      })
    })
    
    console.log('响应状态:', response.status)
    const data = await response.json()
    console.log('响应数据:', data)
    
    if (!response.ok) {
      authError.value = data.error || '认证失败'
      return
    }
    
    // 保存token和用户信息（包括角色）
    localStorage.setItem('token', data.access_token)
    localStorage.setItem('username', username.value)
    localStorage.setItem('userRole', isLogin.value ? data.role : role.value) // 登录时使用后端返回的角色，注册时使用选择的角色
    user.value = { 
      name: username.value,
      role: isLogin.value ? data.role : role.value // 登录时使用后端返回的角色，注册时使用选择的角色
    }
    
    // 关闭模态框
    showAuthModal.value = false
    
    // 获取用户的对话历史
    if (isLogin.value) {
      await fetchConversations()
    }
  } catch (error) {
    console.error('Auth error:', error)
    authError.value = '服务器错误，请稍后再试'
  }
}

// 退出登录
const logout = () => {
  user.value = null
  localStorage.removeItem('token')
  localStorage.removeItem('username')
  localStorage.removeItem('userRole')
  // 关闭管理员面板
  showAdminPanel.value = false
  // 清空对话历史
  conversations.value = [
    {
      id: '1',
      title: '新对话1',
      messages: [
        {
          type: 'assistant',
          content: '你好！我是多功能智能助手，可以回答问题、提供知识、规划任务、进行情感交流、健康咨询以及文化学习。有什么我可以帮到你的吗？',
          timestamp: new Date().toISOString()
        }
      ],
      page_type: 'chat'
    }
  ]
  currentConversationId.value = '1'
  nextId.value = 2
}

// 对话管理
const conversations = ref([
  {
    id: '1',
    title: '新对话1',
    messages: [
      {
        type: 'assistant',
        content: '你好！我是多功能智能助手，可以回答问题、提供知识、规划任务、进行情感交流、健康咨询以及文化学习。有什么我可以帮到你的吗？',
        timestamp: new Date().toISOString()
      }
    ],
    page_type: 'chat'
  }
])

const nextId = ref(2)
const currentConversationId = ref('1')  // 设置为第一个对话的ID
const showHistoryModal = ref(false)

// 获取用户的对话历史
const fetchConversations = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    isLoading.value = true
    console.log(`正在获取页面类型 ${currentPage.value} 的对话历史`)
    
    // 添加当前页面类型作为查询参数
    const response = await fetch(`${API_BASE_URL}/conversations?page_type=${currentPage.value}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (!response.ok) {
      console.error(`获取对话历史失败: ${response.status} ${response.statusText}`)
      return
    }
    
    const data = await response.json()
    console.log(`获取到 ${data.length} 条对话历史，页面类型: ${currentPage.value}`)
    
    // 验证数据格式
    const validData = data.filter(conv => {
      const isValid = conv && conv.id && Array.isArray(conv.messages) && conv.page_type === currentPage.value
      if (!isValid) {
        console.warn(`发现无效的对话数据:`, conv)
      }
      return isValid
    })
    
    // 如果有历史对话，则更新对话列表
    if (validData.length > 0) {
      conversations.value = validData
      currentConversationId.value = validData[0].id
      nextId.value = validData.length + 1
      console.log(`已设置当前对话ID: ${currentConversationId.value}`)
    } else {
      // 如果没有有效的历史对话，创建一个新的
      console.log(`没有找到有效的历史对话，创建新对话`)
      handleNewChat()
    }
  } catch (error) {
    console.error('获取对话历史出错:', error)
  } finally {
    isLoading.value = false
  }
}

// 显示历史对话
const handleShowHistory = () => {
  // 检查用户是否已登录
  if (!checkUserLoggedIn()) {
    // 如果未登录，显示登录弹窗
    openAuth(true)
    return
  }
  
  showHistoryModal.value = true
}

// 关闭历史对话模态框
const closeHistoryModal = () => {
  showHistoryModal.value = false
}

// 切换对话
const switchConversation = (id) => {
  const conversation = conversations.value.find(conv => conv.id === id);
  
  // 如果找到了对话，且该对话有页面类型信息
  if (conversation && conversation.page_type) {
    // 如果对话所属的页面类型与当前页面类型不同，则先切换页面
    if (conversation.page_type !== currentPage.value) {
      console.log(`从 ${currentPage.value} 页面切换到 ${conversation.page_type} 页面`);
      currentPage.value = conversation.page_type;
      // 切换页面后，需要重新获取该页面的对话列表
      fetchConversations().then(() => {
        // 加载完成后，设置当前对话ID
        currentConversationId.value = id;
      });
    } else {
      // 如果是同一页面，直接切换对话
      currentConversationId.value = id;
    }
  } else {
    // 如果没找到对话或没有页面类型信息，直接切换ID
    currentConversationId.value = id;
  }
  
  // 关闭历史对话模态框
  showHistoryModal.value = false;
}

// 格式化消息预览，处理文本、图片和音频内容
const formatMessagePreview = (message) => {
  if (!message || !message.content) return '';
  
  // 如果消息内容是字符串
  if (typeof message.content === 'string') {
    const content = message.content.trim();
    
    // 检查是否为图片 - Markdown格式
    if (content.startsWith('![') && content.includes('](') && content.endsWith(')')) {
      return '[图片]';
    }
    
    // 检查是否为图片 - HTML标签
    if (content.startsWith('<img ') && content.includes('src="')) {
      return '[图片]';
    }
    
    // 检查是否为图片 - 纯URL
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
    if (imageExtensions.some(ext => content.toLowerCase().endsWith(ext)) && 
        (content.startsWith('http') || content.startsWith('data:image'))) {
      return '[图片]';
    }
    
    // 检查是否为音频 - Markdown格式
    if (content.startsWith('[audio](') && content.endsWith(')')) {
      return '[音频]';
    }
    
    // 检查是否为音频 - HTML标签
    if (content.includes('<audio ') && content.includes('</audio>')) {
      return '[音频]';
    }
    
    // 检查是否为音频 - 纯URL
    const audioExtensions = ['.mp3', '.wav', '.ogg', '.m4a', '.aac'];
    if (audioExtensions.some(ext => content.toLowerCase().endsWith(ext)) && 
        (content.startsWith('http') || content.startsWith('data:audio'))) {
      return '[音频]';
    }
    
    // 检查上传文件/图片信息
    if (content.includes('上传了图片') || content.includes('上传了文件') || content.includes('上传了音频')) {
      const match = content.match(/\[.*?(上传了.+?)\]/);
      if (match && match[1]) {
        return match[1]; // 返回上传文件/图片的描述
      }
    }
    
    // 去除Markdown链接和图片
    let cleanContent = content.replace(/\!\[.*?\]\(.*?\)/g, '[图片]'); // 替换图片
    cleanContent = cleanContent.replace(/\[.*?\]\(.*?\)/g, '$1'); // 保留链接文本
    
    // 去除Markdown代码块
    cleanContent = cleanContent.replace(/```[\s\S]*?```/g, '[代码]');
    cleanContent = cleanContent.replace(/`.*?`/g, '$&'); // 保留行内代码
    
    // 去除JSON结构
    cleanContent = cleanContent.replace(/\{.*\}/g, '[数据]');
    
    // 去除多余空格和换行
    cleanContent = cleanContent.replace(/\s+/g, ' ');
    
    // 限制长度
    return cleanContent.length > 50 ? cleanContent.substring(0, 50) + '...' : cleanContent;
  }
  
  // 如果是对象类型或其他类型，返回简单描述
  return message.type === 'user' ? '用户消息' : 'AI回复';
}

// 删除对话
const deleteConversation = async (id) => {
  if (conversations.value.length === 1) return // 至少保留一个
  
  const token = localStorage.getItem('token')
  if (token) {
    try {
      // 添加当前页面类型作为查询参数
      const response = await fetch(`${API_BASE_URL}/conversations/${id}?page_type=${currentPage.value}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        console.error('Failed to delete conversation')
        return
      }
    } catch (error) {
      console.error('Error deleting conversation:', error)
    }
  }
  
  const idx = conversations.value.findIndex(c => c.id === id)
  if (idx !== -1) {
    conversations.value.splice(idx, 1)
    // 如果删除的是当前对话，切换到第一个
    if (currentConversationId.value === id) {
      currentConversationId.value = conversations.value[0].id
    }
  }
}

// 当前对话对象
const currentConversation = () => conversations.value.find(c => c.id === currentConversationId.value) || conversations.value[0]

// 聊天消息更新
const handleUpdateMessages = (messages) => {
  const conv = currentConversation()
  if (conv) conv.messages = messages
}

// 检查是否已登录
onMounted(() => {
  const token = localStorage.getItem('token')
  if (token) {
    try {
      // 从localStorage获取用户信息
      const userRole = localStorage.getItem('userRole') || 'user'
      // 设置用户信息
      user.value = { 
        name: localStorage.getItem('username') || 'User',
        role: userRole
      }
      fetchConversations()
    } catch (error) {
      console.error('Error loading user data:', error)
      // 如果出错，清除token
      localStorage.removeItem('token')
    }
  }
})
</script>

<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-purple-50 to-indigo-50 flex flex-col relative overflow-hidden">
    <!-- 装饰性背景元素 -->
    <div class="absolute top-20 right-20 w-64 h-64 bg-gradient-to-br from-blue-300/20 to-indigo-300/20 rounded-full blur-3xl float-bubble"></div>
    <div class="absolute bottom-20 left-40 w-72 h-72 bg-gradient-to-tr from-purple-300/20 to-pink-300/20 rounded-full blur-3xl float-bubble" style="animation-delay: 2s;"></div>
    <div class="absolute top-1/2 left-1/4 w-48 h-48 bg-gradient-to-br from-amber-300/10 to-orange-300/10 rounded-full blur-3xl float-bubble" style="animation-delay: 1s;"></div>
    
    <!-- 小装饰点 -->
    <div class="absolute top-40 left-1/3 w-6 h-6 bg-blue-400/30 rounded-full float"></div>
    <div class="absolute top-80 right-1/4 w-4 h-4 bg-purple-400/30 rounded-full float" style="animation-delay: 1s;"></div>
    <div class="absolute bottom-40 right-1/3 w-5 h-5 bg-pink-400/30 rounded-full float" style="animation-delay: 2s;"></div>
    <div class="absolute bottom-60 left-1/4 w-3 h-3 bg-indigo-400/30 rounded-full float" style="animation-delay: 3s;"></div>
    
    <!-- 装饰图形 -->
    <div class="absolute top-1/3 right-1/3 w-8 h-8 border-2 border-emerald-300/30 rotate-45 float-bubble" style="animation-delay: 1.5s;"></div>
    <div class="absolute bottom-1/3 left-2/3 w-6 h-6 border-2 border-amber-300/30 rounded-full float-bubble" style="animation-delay: 2.5s;"></div>
    <div class="absolute top-2/3 left-1/5 w-10 h-10 border-2 border-cyan-300/30 rotate-12 float-bubble" style="animation-delay: 3.5s;"></div>
    
    <!-- 头部区域 -->
    <header class="bg-white/80 backdrop-blur-sm shadow-md relative mb-6 z-10 glass">
      <div class="px-6 py-5 flex items-center gap-4">
        <div class="w-14 h-14 rounded-2xl bg-gradient-to-r from-blue-500 to-indigo-600 flex items-center justify-center text-white shadow-lg transform hover:scale-105 transition-transform pulse">
          <i class="fas fa-robot text-2xl"></i>
        </div>
        <div>
          <h1 class="text-2xl font-bold text-gradient-rainbow">
            多功能智能助手
          </h1>
          <p class="text-gray-500">基于 LangChain 的多模型集成智能对话系统</p>
        </div>
        <div class="flex-1"></div>
        <div class="flex items-center gap-4 mr-4">
          <template v-if="user">
            <span class="text-blue-700 font-semibold">{{ user.name }}</span>
            <!-- 管理员按钮 -->
            <button 
              v-if="user.role === 'admin'"
              @click="showAdminPanel = true" 
              class="px-4 py-2 rounded-lg bg-gradient-to-r from-purple-600 to-indigo-600 text-white hover:from-purple-700 hover:to-indigo-700 transition-all duration-300 hover:shadow-md shine-effect"
            >
              后台管理系统
            </button>
            <button @click="logout" class="px-4 py-2 rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-700 transition-all duration-300 hover:shadow-md shine-effect">退出登录</button>
          </template>
          <template v-else>
            <button @click="openAuth(true)" class="px-5 py-2 rounded-lg bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-semibold shadow-md hover:shadow-lg transition-all duration-300 shine-effect">登录/注册</button>
          </template>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <div class="flex-1 flex relative z-10 overflow-hidden">
      <!-- 侧边栏 -->
      <div class="w-[340px] flex-shrink-0 px-4">
        <SideMenu
          :menu-items="menuItems"
          :current-page="currentPage"
          @page-change="handlePageChange"
          @new-chat="handleNewChat"
          @show-history="handleShowHistory"
        />
      </div>

      <!-- 聊天区域容器 -->
      <main class="flex-1 px-4 overflow-hidden">
        <div class="max-w-[1280px] mx-auto">
          <ChatContainer
            :current-page="currentPage"
            :messages="currentConversation().messages"
            :conversation-id="currentConversationId"
            @update-messages="handleUpdateMessages"
            @loading-change="isLoading = $event"
            @show-auth="openAuth(true)"
          />
        </div>
      </main>
    </div>

    <!-- 登录/注册弹窗 -->
    <div v-if="showAuthModal" class="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50">
      <div class="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 w-96 relative glass scale-in">
        <button class="absolute right-4 top-4 text-gray-400 hover:text-gray-600" @click="closeAuth">
          <i class="fas fa-times"></i>
        </button>
        <h2 class="text-xl font-bold mb-5 text-center text-gradient-blue">{{ isLogin ? '登录' : '注册' }}</h2>
        <form @submit.prevent="handleAuth" class="flex flex-col gap-4">
          <input v-model="username" type="text" placeholder="用户名" class="border rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-400 bg-white/80" required>
          <input v-model="password" type="password" placeholder="密码" class="border rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-400 bg-white/80" required>
          <input v-if="!isLogin" v-model="email" type="email" placeholder="邮箱" class="border rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-400 bg-white/80" required>
          
          <!-- 角色选择（仅在注册时显示） -->
          <div v-if="!isLogin" class="flex items-center gap-4 justify-center">
            <label class="flex items-center gap-2 cursor-pointer">
              <input type="radio" v-model="role" value="user" class="w-4 h-4 text-blue-600" checked>
              <span>普通用户</span>
            </label>
            <label class="flex items-center gap-2 cursor-pointer">
              <input type="radio" v-model="role" value="admin" class="w-4 h-4 text-blue-600">
              <span>管理员</span>
            </label>
          </div>
          
          <p v-if="authError" class="text-red-500 text-sm">{{ authError }}</p>
          
          <button type="submit" class="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white rounded-lg py-3 font-semibold shadow-md hover:shadow-lg transition-all duration-300 shine-effect">{{ isLogin ? '登录' : '注册' }}</button>
        </form>
        <div class="text-center mt-5">
          <button class="text-blue-600 hover:text-blue-800 hover:underline text-sm transition-colors" @click="isLogin = !isLogin">
            {{ isLogin ? '没有账号？注册' : '已有账号？登录' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 历史对话弹窗 -->
    <div v-if="showHistoryModal" class="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50">
      <div class="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-6 w-96 relative glass scale-in">
        <button class="absolute right-4 top-4 text-gray-400 hover:text-gray-600" @click="closeHistoryModal">
          <i class="fas fa-times"></i>
        </button>
        <h2 class="text-lg font-bold mb-4 text-gradient-purple">历史对话</h2>
        <div class="flex mb-4 border-b border-gray-200">
          <div 
            v-for="item in menuItems" 
            :key="item.id"
            class="px-3 py-2 cursor-pointer text-sm flex items-center gap-1"
            :class="{'text-blue-600 border-b-2 border-blue-600 font-medium': currentPage === item.id}"
            @click="handlePageChange(item.id)"
          >
            <i :class="['fas', item.icon]"></i>
            <span class="hidden sm:inline">{{ item.name }}</span>
          </div>
        </div>
        <div class="max-h-[400px] overflow-y-auto">
        <ul class="space-y-2">
          <li v-for="conv in conversations" :key="conv.id" class="flex items-center justify-between p-3 rounded-xl hover:bg-blue-50 transition-all duration-300" :class="{ 'bg-blue-100 shadow-sm': conv.id === currentConversationId }">
              <!-- 显示对话标题，截断过长内容 -->
              <div class="flex-1 cursor-pointer" @click="switchConversation(conv.id)">
                <div class="truncate max-w-[180px] font-medium">{{ conv.title || '新对话' }}</div>
                <div class="text-xs text-gray-500 truncate" v-if="conv.messages && conv.messages.length > 0">
                  {{ formatMessagePreview(conv.messages[0]) }}
                </div>
              </div>
            <div class="flex items-center gap-2">
              <button v-if="conversations.length > 1" @click="deleteConversation(conv.id)" class="text-red-400 hover:text-red-600 transition-colors"><i class="fas fa-trash"></i></button>
              <button v-if="conv.id !== currentConversationId" @click="switchConversation(conv.id)" class="text-blue-500 hover:text-blue-700 hover:underline text-xs transition-colors">切换</button>
              <span v-else class="text-xs text-gray-400">当前</span>
            </div>
          </li>
        </ul>
          <div v-if="conversations.length === 0" class="text-center py-4 text-gray-500">
            该页面暂无对话记录
          </div>
        </div>
      </div>
    </div>

    <!-- 管理员面板 -->
    <AdminPanel 
      :visible="showAdminPanel" 
      @close="showAdminPanel = false"
    />

    <!-- 加载状态 -->
    <LoadingState v-if="isLoading" />
  </div>
</template>

<style>
body {
  @apply bg-slate-50 text-gray-900;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 添加全局动画 */
@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
  100% {
    transform: translateY(0px);
  }
}

.float {
  animation: float 6s ease-in-out infinite;
}
</style>
